<template>
  <div>
    <el-table
      :data="tableData"
      border
      stripe
      :span-method="arraySpanMethod"
      ref="table"
    >
      <el-table-column label="学院" prop="college" align="center" />
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="年龄" prop="age" align="center" />
      <el-table-column label="性别" prop="sex" align="center">
        <template slot-scope="scope">
          {{ scope.row.sex == "1" ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱" prop="email" align="center" />
    </el-table>
  </div>
</template>
<script>
export default {
  name: "tableSpan",
  data() {
    return {
      tableData: [
        {
          college: "计算机",
          name: "张三",
          age: 21,
          sex: 1,
          email: "123@gmail.com",
        },
        {
          college: "计算机",
          name: "李四",
          age: 21,
          sex: 0,
          email: "127@gmail.com",
        },
        {
          college: "人工智能",
          name: "赵五",
          age: 20,
          sex: 1,
          email: "127@gmail.com",
        },
      ],
      pos: 0,
      spanArr: [],
    };
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
        this.pos = 0
        this.spanArr = []
        this.getSpanCombine(this.tableData)
    },
 // 计算合并下标
 arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      // 判断是否是前4行数据
      if (column.label === "学院" ) {
        this.$refs.table.doLayout()
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    // 合并表格
    getSpanCombine(data) {
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          if (data[i].college === data[i - 1].college) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
  },
};
</script>
